package src.tree;

import java.util.LinkedList;
import java.util.Queue;

public class no222 {//完全二叉树的节点个数

    //迭代法，层序遍历
    public int countNodes(TreeNode root) {

        if (root == null) return 0;
        int count = 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                count++;
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);

            }
        }
        return count;
    }

    //递归遍历
    public int countNodes2(TreeNode root) {
        if (root == null) return 0;
        int left = countNodes2(root.left);
        int right = countNodes2(root.right);
        return left + right + 1;
    }

}
